package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ArticleMapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.ArticleService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void addArticle(Article article) {
        //获取当前登录用户
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        //获取并设置创建更新时间
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.addArticle(article);

    }

    @Override
    public PageBean<Article> pageQueryArticle(Integer pageNum,Integer pageSize,
                                              Integer categoryId,String state) {
        //创建PagBean对象
        PageBean<Article> pageBean = new PageBean<>();

        //开启分页插件
        PageHelper.startPage(pageNum,pageSize);
        //获取用户id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> articleList = articleMapper.pageQueryArticle(userId,categoryId,state);
        //Page中提供了方法来获取当前页数的数据，和统计信息
        Page<Article> p = (Page<Article>) articleList;
        pageBean.setTotal(p.getTotal());
        pageBean.setItems(p.getResult());
        return pageBean;
    }

    @Override
    public Article articleDetailById(Integer id) {
        Article article = articleMapper.articleDetailById(id);
        return article;
    }

    @Override
    public void updateArticle(Article article) {
        //获取当前用户信息
//        Map<String,Object> map = ThreadLocalUtil.get();
//        Integer userId = (Integer) map.get("id");
//        article.setCreateUser(userId);
        //设置更新时间
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.updateArticle(article);

    }

    @Override
    public void deleteArticleById(Integer id) {
        articleMapper.deleteArticleById(id);
    }
}
